<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :width="1200"
    okText="确定"
    @register="register"
    :title="props.title"
    @visible-change="handleVisibleChange"
  >
    <div class="tag-box">
      <div class="main-nav">
        <div class="search-box">
          <a-input-search
            v-model:value="searchDriver"
            placeholder="搜索"
            :allowClear="true"
            @search="onSearchDriver"
          />
        </div>
        <BasicTree
          :loading="loading"
          title=""
          ref="treeRefPro"
          :treeData="treeDataPro"
          :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
          :onSelect="handleTreeSelect"
        />
      </div>
      <div class="main-content">
        <BasicTable @register="registerTable">
          <template #toolbar>
            <a-input-search
              v-model:value="searchValue"
              placeholder="请输入搜索的变量"
              style="width: 200px"
              :allowClear="true"
              @search="onSearch"
              v-if="isShowSearch"
            />
          </template>
        </BasicTable>
      </div>
    </div>
  </BasicModal>
</template>

<script setup lang="ts">
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import { getRunTimeDriverTree, getRunTimeTagInfo, getDataType } from '/@/api/tag/index';
  import { ref, nextTick, reactive, unref, computed } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useMessage } from '/@/hooks/web/useMessage';

  const props = defineProps({
    title: {
      type: String,
      default: '',
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
  });

  const [register] = useModal();
  const emit = defineEmits(['checkTag']);
  let treeDataPro: any = ref([]);
  let typeOptions: any = reactive([]);
  let searchDriver = ref('');
  let searchValue = ref('');
  let isSearch = false;
  let curType = ref(0);
  let loading = ref(false);
  let BasicTableTitle: any = ref('');
  const treeRefPro = ref<Nullable<TreeActionType>>(null);
  let tableParams: any = reactive({
    driveId: '',
    groupId: '',
  });
  // 表单数据
  let columns: BasicColumn[] = [
    {
      fixed: 'left',
      title: '标签名',
      dataIndex: 'Name',
    },
    {
      title: '全称',
      dataIndex: 'FullName',
    },
    {
      title: '地址',
      dataIndex: 'Address',
    },
    {
      title: '数据类型',
      dataIndex: 'DataTypeCn',
    },
  ];
  //   setSelectedRowKeys  设置选中行
  // getSelectRows 获取选择行
  // clearSelectedRowKeys 清空选中行
  const [
    registerTable,
    { getPaginationRef, setPagination, reload, getSelectRows, clearSelectedRowKeys },
  ] = useTable({
    title: BasicTableTitle,
    api: getRunTimeTagInfo,
    immediate: false,
    columns,
    canResize: false,
    rowSelection: {
      type: props.isMultiple ? 'checkbox' : 'radio',
      checkStrictly: true,
      // getCheckboxProps(record: Recordable){
      //   return handleGetCheckProps(record)
      // },
    },
    showIndexColumn: false,
    rowKey: 'FullName',
    striped: true,
    bordered: true,
    fetchSetting: {
      pageField: 'PageNO',
      sizeField: 'PageSize',
      totalField: 'TotalRows',
      listField: 'Rows',
    },
    beforeFetch: () => {
      return [
        {
          SearchValue: isSearch ? searchValue.value : '',
          DriverKey: tableParams.driveId,
          GroupKey: tableParams.groupId,
          PageNO: getPaginationRef().current || 1,
          PageSize: getPaginationRef().pageSize || 50,
        },
      ];
    },
    afterFetch: (v) => {
      // console.log(`output->v`, v);
      // setPagination({
      //   total: v.TotalRows,
      // });
      return v.map((item) => {
        let targetTypes = typeOptions.filter((v) => v.Value === item.DataType);
        item.DataTypeCn = targetTypes.length > 0 ? targetTypes[0].Key : '';
        return item;
      });
    },
  });
  const isShowSearch = computed(() => curType.value === 2 || curType.value === 1);
  const { createMessage } = useMessage();
  // onMounted(async () => {

  // });
  function getTree() {
    const tree = unref(treeRefPro);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  function eachTree(treeDatas: any[]) {
    treeDatas.forEach((element) => {
      element.title = element.Name;
      switch (element.Type) {
        case 0:
          element.icon = 'ant-design:home-outlined';
          break;
        case 1:
          element.icon = 'ant-design:database-outlined';
          break;
        case 2:
          element.icon = 'ant-design:bars-outlined';
          break;
        case 3:
          element.icon = 'ant-design:folder-outlined';
          break;
        default:
          break;
      }
      if (element.Children) eachTree(element.Children);
    });
  }
  // 搜索方法
  function onSearch() {
    isSearch = ['', null, undefined].indexOf(searchValue.value) === -1;

    setPagination({
      current: 1,
    });
    reload();
  }
  // 搜索设备
  function onSearchDriver() {
    initData();
  }
  async function initData() {
    loading.value = true;
    let resByTree = await getRunTimeDriverTree(searchDriver.value ? [searchDriver.value] : [null]);
    eachTree(resByTree);
    treeDataPro.value = resByTree || [];
    nextTick(() => {
      getTree().filterByLevel(1);
    });
    loading.value = false;
  }
  function handleTreeSelect(e, info) {
    BasicTableTitle.value = info.node?.title || '';
    searchValue.value = '';
    let { Type, Children = [] } = info.node;
    curType.value = +Type;
    if ((Type === 1 && Children && Children.length > 0) || Type === 2) {
      let targetGroup = Type === 1 ? Children[0] : info.node;
      BasicTableTitle.value = targetGroup.title;
      tableParams.groupId = targetGroup.Key;
      tableParams.driveId = targetGroup.Parentkey;
    } else {
      BasicTableTitle.value = '';
      tableParams.groupId = '-1';
      tableParams.driveId = '-1';
    }
    setPagination({
      current: 1,
    });
    reload();
    clearSelectedRowKeys();
  }
  async function handleSubmint() {
    let res = await getSelectRows();
    if (res.length === 0) {
      createMessage.warning('请选择关联变量');
    } else {
      clearSelectedRowKeys();
      emit('checkTag', res);
    }
  }
  async function handleVisibleChange(visible) {
    if (visible) {
      await initData();
      typeOptions = await getDataType();
      // if(props.info.Select)
    } else {
      clearSelectedRowKeys();
    }
  }
</script>

<style lang="less" scoped>
  .tag-box {
    width: 100%;
    position: relative;

    min-height: 600px;
    background-color: #fff;

    .main-nav {
      position: absolute;
      top: 0;
      left: 0;
      width: 240px;
      height: 100%;
      padding: 8px;
      box-sizing: border-box;
      background-color: rgba(8, 30, 66, 0.04);
      border-radius: 3px;
    }

    .main-content {
      position: relative;
      height: 100%;
      margin-left: 260px;
    }
  }
</style>
